package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractService contractService;
    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;

    @RequestMapping(value = "/list",name ="查询某个购销合同下货物的数据")
    public String findAll(String contractId,@RequestParam(defaultValue = "1",name = "page") int pageNum, @RequestParam(defaultValue = "10") int pageSize){

//        页面中需要用到的数据：
//        1、当前购销合同下的货物数据PageInfo
//        2、用来生产货物的工厂数据 通过ctype查询
//        3、合同id，为了保存货物时关联合同

//        1、当前购销合同下的货物数据PageInfo   select * from co_contract_product where contact_id=??
        ContractProductExample example = new ContractProductExample();
        example.createCriteria().andContractIdEqualTo(contractId);
        PageInfo<ContractProduct> pageInfo = contractProductService.findAll(example,pageNum,pageSize);
        request.setAttribute("page",pageInfo);
//        2、用来生产货物的工厂数据 通过ctype查询  select * from co_factory where ctype='货物'
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);

//        3、合同id，为了保存货物时关联合同
        request.setAttribute("contractId",contractId);

        return "cargo/product/product-list";
    }

    @RequestMapping(value = "/toUpdate",name ="进入编辑购销合同下货物页面")
    public String toUpdate(String id){
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct",contractProduct);


        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList",factoryList);

        return "cargo/product/product-update";
    }


    @Autowired
    private FileUploadUtil fileUploadUtil;

    @RequestMapping(value = "/edit",name ="保存购销合同下货物方法")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto){
//        处理图片
        String imagePath = null;
        try {
            imagePath = fileUploadUtil.upload(productPhoto);
        } catch (Exception e) {
            System.out.println(e.getMessage());

        }
        contractProduct.setProductImage(imagePath);

        if(StringUtils.isEmpty(contractProduct.getId())){
            contractProduct.setId(UUID.randomUUID().toString());
            contractProduct.setCompanyId(getCompanyId());
            contractProduct.setCompanyName(getCompanyName());
            contractProduct.setCreateTime(new Date());
            contractProductService.save(contractProduct);
        }else{
            contractProductService.update(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractProduct.getContractId();  // 重定向到货物的列表页面
    }

    //    /cargo/contractProduct/list.do?contractId=a2d5f5d4-59a9-4e70-bd76-a30f142afd9b
    @RequestMapping(value = "/delete",name ="删除购销合同下货物方法")
    public String delete(String id,String contractId){
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }

    @RequestMapping(value = "/toImport",name ="进入到上传货物的页面")
    public String toImport(String contractId){
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }

    @RequestMapping(value = "/import",name ="上传货物的方法")
    public String importXls(String contractId,MultipartFile file) throws Exception{
//       读取excel中的内容，把每一行转成contractProduct对象并且保存到表中
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        Sheet sheet = workbook.getSheetAt(0);
        int lastRowIndex = sheet.getLastRowNum();
        ContractProduct contractProduct = null;
        Row row = null;
        List<ContractProduct> list = new ArrayList<>();
        for (int i = 1; i <= lastRowIndex; i++) {
//            生产厂家	货号	数量	包装单位(PCS/SETS)	装率	箱数	单价	货物描述	要求
            row = sheet.getRow(i);
            contractProduct = new ContractProduct();
            String fatoryName = row.getCell(1).getStringCellValue();//生产厂家
            contractProduct.setFactoryName(fatoryName);

            String productNo = row.getCell(2).getStringCellValue(); //货号
            contractProduct.setProductNo(productNo);

            Integer cnumber = ((Double)row.getCell(3).getNumericCellValue()).intValue(); //数量
            contractProduct.setCnumber(cnumber);

            String packingUnit = row.getCell(4).getStringCellValue(); //包装单位(PCS/SETS)
            contractProduct.setPackingUnit(packingUnit);

            String loadingRate = ((Double)row.getCell(5).getNumericCellValue()).toString(); //装率
            contractProduct.setLoadingRate(loadingRate);

            Integer boxNum =((Double)row.getCell(6).getNumericCellValue()).intValue(); //箱数
            contractProduct.setBoxNum(boxNum);

            Double price = (Double)row.getCell(7).getNumericCellValue(); //单价
            contractProduct.setPrice(price);

            String productDesc = row.getCell(8).getStringCellValue();
            contractProduct.setProductDesc(productDesc);

            String productRequest = row.getCell(9).getStringCellValue();
            contractProduct.setProductRequest(productRequest);

//            添加默认值 非常重要的是购销合同的id
            contractProduct.setId(UUID.randomUUID().toString());
            contractProduct.setCompanyId(getCompanyId());
            contractProduct.setCompanyName(getCompanyName());
            contractProduct.setCreateTime(new Date());
            contractProduct.setContractId(contractId);

//            contractProductService.save(contractProduct);
//            弊端1：无法保证事务的原子性（这一批货物上传）
//            弊端2：数据量比较大时，会重复不断地打开和关闭很多次事务

            list.add(contractProduct);

        }
        contractProductService.saveList(list);


        return "redirect:/cargo/contractProduct/list.do?contractId="+contractId;
    }


}
